﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRM.DAL.Ali;
using CRM.UTIL;

namespace TaskScheduledRefresh
{
    class Program
    {
        /// <summary>
        /// 根据Hashtable 绑定对象
        /// </summary>
        /// <param name="htFirst"></param>
        /// <param name="enID"></param>
        /// <param name="isAll"></param>
        /// <param name="entity"></param>
        public static void InitDataEntity(Hashtable htFirst, string enID, bool isAll, ref CRM.MODEL.Ali.EditAli_Orders entity)
        {
            var arrayList = htFirst["dataList"] as ArrayList;
            if (arrayList != null)
            {

                var ht = new Hashtable();

                //foreach (
                //    Hashtable item in
                //        arrayList.Cast<Hashtable>()
                //            .Where(
                //                item =>
                //                    item["productSnapshotUrl"].ToString()
                //                        .Contains("/" + enIdArr[i] + ".html")))
                //{
                //    ht = item;
                //}
                foreach (
                            Hashtable item in
                                arrayList.Cast<Hashtable>()
                                    .Where(
                                        item =>
                                            item["snapshotId"].ToString() == enID))
                {
                    ht = item;
                }



                //insStu.ORDERID_VALUE = ht["orderId"];
                entity.BizID_VALUE = ht["bizId"];
                entity.ORDERDATE_VALUE = ht["orderDate"];
                entity.PRODUCTNAME_VALUE = ht["productName"];
                entity.PRODUCTSKUINFO_VALUE = ht["skuInfo"];
                entity.PRODUCTSNAPSHOTURL_VALUE = ht["productSnapshotUrl"];
                entity.PRODUCTPROPERTIES_VALUE = ht["productProperties"];
                entity.PRODUCTTYPE_VALUE = ht["productLeafCategoryId"];
                entity.ORDERFROMTYPE_VALUE = (int)OrderFromType.Aliexpress;
                var orderHt = ht["orderInfo"] as Hashtable;
                if (orderHt != null)
                {
                    if (orderHt["sellerAliId"] != null)
                    {
                        entity.SELLERALIID_VALUE = orderHt["sellerAliId"];
                    }
                    if (orderHt["buyerAliId"] != null)
                    {
                        entity.BUYERALIID_VALUE = orderHt["buyerAliId"];
                    }
                }
                if (ht["warrantyInForceStatus"] != null)
                {
                    if (ht["warrantyInForceStatus"].ToString() == "enabled")
                        entity.EFFECTIVE_VALUE = true;
                    var warrantyHt = ht["warrantyInfo"] as Hashtable;
                    if (warrantyHt != null && warrantyHt["judgeInforceTime"] != null)
                    {
                        entity.EFFECTIVEDATE_VALUE = warrantyHt["judgeInforceTime"];
                    }
                    else
                    {
                        entity.EFFECTIVEDATE_VALUE = ht["judgeInforceTime"];
                    }
                }

                if (isAll)
                {
                    if (ht["productProperties"] != null &&
                        !string.IsNullOrEmpty(ht["productProperties"].ToString()))
                    {
                        try
                        {
                            var jsonData = JSON.Decode(ht["productProperties"].ToString()) as Hashtable;
                            if (jsonData != null)
                            {
                                entity.BRANDNAMEVALUE = jsonData["Brand Name"];
                                entity.PRODUCTMODELVALUE = jsonData["Model"];
                                if (string.IsNullOrEmpty(entity.PRODUCTMODELVALUE.ToString()))
                                {
                                    foreach (var key in jsonData.Keys)
                                    {
                                        if ((key.ToString().ToLower().EndsWith("model") ||
                                             key.ToString().Trim().ToLower() == "model" ||
                                             key.ToString().Trim().ToLower() == "model number")
                                            && jsonData[key] != null
                                            && !string.IsNullOrEmpty(jsonData[key].ToString()))
                                        {
                                            entity.PRODUCTMODELVALUE = jsonData[key];
                                        }
                                    }
                                }
                                //手机
                                if (entity.PRODUCTTYPE_VALUE.ToString() ==
                                    (((int)ProductType.Phone).ToString(CultureInfo.InvariantCulture)))
                                {
                                    entity.ITEMCONDITIONVALUE = jsonData["Item Condition"];
                                    entity.RAMVALUE = jsonData["RAM"];
                                    entity.ROMVALUE = jsonData["ROM"];
                                    entity.DISPLAYSIZEVALUE = jsonData["Display Size"];
                                    entity.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                    entity.BATTERYCAPACITYVALUE = jsonData["Battery Capacity(mAh)"];
                                    entity.CPUVALUE = jsonData["CPU"];
                                    entity.SIZEVALUE = jsonData["Size"];
                                    entity.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                    entity.OSVALUE = jsonData["OS"];
                                }
                                else if (entity.PRODUCTTYPE_VALUE.ToString() ==
                                         (((int)ProductType.TabletPC).ToString(CultureInfo.InvariantCulture)))
                                {
                                    //平板
                                    entity.ITEMCONDITIONVALUE = jsonData["Status"];
                                    entity.RAMVALUE = jsonData["Memory Capacity"];
                                    entity.ROMVALUE = jsonData["Tablet Data Capacity"];
                                    entity.DISPLAYSIZEVALUE = jsonData["Screen Size"];
                                    entity.DISPLAYRESOLUTIONVALUE = jsonData["Display Resolution"];
                                    if (string.IsNullOrEmpty(entity.DISPLAYRESOLUTIONVALUE.ToString()))
                                    {
                                        entity.DISPLAYRESOLUTIONVALUE = jsonData["Display resolution"];
                                    }
                                    entity.BATTERYCAPACITYVALUE = jsonData["Cell Capacity"];
                                    entity.CPUVALUE = jsonData["Processor Manufacture"];
                                    //entity.SIZEVALUE = jsonData["Screen Size"];
                                    entity.OPERATIONSYSTEMVALUE = jsonData["Operation System"];
                                    if (string.IsNullOrEmpty(entity.OPERATIONSYSTEMVALUE.ToString()))
                                    {
                                        entity.OPERATIONSYSTEMVALUE = jsonData["Operating System"];
                                    }
                                    //entity.OSVALUE = jsonData["OS"];
                                }
                            }
                        }
                        catch
                        {
                        }
                    }
                }

                entity.STOREURL_VALUE = ht["storeUrl"];
                //买家国家
                if (ht["country"] != null && !string.IsNullOrEmpty(ht["country"].ToString()))
                {
                    entity.COUNTRY_VALUE = ht["country"];
                }
                //买家省份
                if (ht["province"] != null && !string.IsNullOrEmpty(ht["province"].ToString()))
                {
                    entity.PROVINCE_VALUE = ht["province"];
                }
                //买家城市
                if (ht["city"] != null && !string.IsNullOrEmpty(ht["city"].ToString()))
                {
                    entity.CITY_VALUE = ht["city"];
                }

                entity.STREETADDRESS_VALUE = ht["streetAddress"]; //买家街道
                entity.POSTCODE_VALUE = ht["postCode"]; //买家邮编
                entity.SENDGOODSTIME_VALUE = ht["sendGoodsTime"]; //产品发货时间
                entity.SELLERIDGETGOODSTIME_VALUE = ht["getGoodsTime"]; //产品收货时间
                entity.PRODUCTCOUNT_VALUE = ht["productCount"]; //产品数量
                entity.STATUS_VALUE = ht["status"];
                //交易状态。订单状态： 1.PLACE_ORDER_SUCCESS（下单成功）2.WAIT_SELLER_SEND_GOODS（待卖家发货）3.SELLER_PART_SEND_GOODS（待卖家部分发货）4.WAIT_BUYER_ACCEPT_GOODS（等待买家收货）5.FUND_PROCESSING（资金处理中）6.FINISH（交易成功）
                entity.PRODUCTAMOUNT_VALUE = ht["productAmount"]; //产品金额，分
                entity.SERVICEAMOUNT_VALUE = ht["serviceAmount"]; //保修金额，分
                entity.PAYCURRENCY_VALUE = ht["payCurrency"]; //支付币种
                entity.ORDERCURRENCY_VALUE = ht["orderCurrency"]; //订单币种
                entity.EXCHANGE_VALUE = ht["exchange"]; //汇率
                entity.WARRANTYTYPE_VALUE = ht["warrantyType"];
                //保修类型. 1.warranty_common（普通保修）2.warranty_refund（只退不修）
                entity.SERVICESTARTTIME_VALUE = ht["serviceStartTime"]; //服务开始时间，买家确认收货之前为空
                entity.SERVICEENDTIME_VALUE = ht["serviceEndTime"]; //服务结束时间，买家确认收货之前为空
                entity.WARRANTYSTATUS_VALUE = ht["warrantyStatus"];
                //保修状态 1.notSubmit(未提交)2.create（创建）3.cancel（取消）4.finish（完成）
                entity.NAME_VALUE = ht["name"]; //买家姓名,warrantyStatus=notSubmit时为空
                entity.TELEPHONE_VALUE = ht["telephone"]; //买家电话,warrantyStatus=notSubmit时为空
                entity.DESCRIPTION_VALUE = ht["description"]; //买家保修描述,warrantyStatus=notSubmit时为空
                entity.ATTACHMENTS_VALUE = ht["attachments"];
                //买家保修提交附件，逗号分隔,warrantyStatus=notSubmit时为空
            }
        }
        static void Main(string[] args)
        {
            log("Start Time:" + DateTime.Now);
            int successCount = 0;
            int failCount = 0;
            var sb = new StringBuilder();
            var serv = new RunAliAPI();
            try
            {
                
                var obj = new CRM.BLL.Ali.Ali_OrdersB();
                var stu = new CRM.MODEL.Ali.GetAli_Orders
                {
                    ORDERSTRING_VALUE = " o.ID Asc",
                    EFFECTIVE_VALUE = true,
                    CURRENTPAGEINDEX_VALUE = 1,
                    PAGESIZE_VALUE = 100000
                };
                var dt = obj.GetAli_Orders(ref stu);
                for (var i = 0; i < dt.Rows.Count; i++)
                {
                    var dr = dt.Rows[i];
                    try
                    {
                        var entity = new CRM.MODEL.Ali.EditAli_Orders
                        {
                            ACTION_VALUE = "Update",
                            ID_VALUE = dr["ID"].ToString()
                        };
                        var resJson = serv.GetOrderInfo(dr["OrderId"].ToString(), false, false);

                        var htFirst = JSON.Decode(resJson) as Hashtable;
                        if (htFirst["success"].ToString().ToLower() == "true")
                        {

                            InitDataEntity(htFirst, dr["ENid"].ToString(),
                                false, ref entity);

                            obj.EditAli_Orders(ref entity);


                            successCount++;
                        }
                        else
                        {
                            failCount++;
                            sb.Append("第" + (i + 1) + "行调用Ali接口失败;");
                        }
                        var str = "成功数量：" + successCount + ",ID=" + dr["ID"].ToString();
                        Console.WriteLine(str);
                        //log(str);
                    }
                    catch (Exception ex)
                    {
                        failCount++;
                        var msg = "第" + (i + 1) + "行异常：" + ex.Message + "，ID：" + dr["ID"].ToString();
                        sb.Append(msg);
                        //log(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                log(ex.Message + ex.StackTrace);
            }
            log(string.Format("更新成功行数{0},失败行数{1},出错信息:{2}", successCount, failCount, sb.ToString()));
            log("End Time:" + DateTime.Now);
        }
        public static string GetUpLoadDirPath()
        {
            var folder = "File";
            string dirPath = AppDomain.CurrentDomain.BaseDirectory + folder;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            //String ymd = DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo);
            dirPath += "\\" + DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + "\\";
            folder += "\\" + DateTime.Now.ToString("yyyy", DateTimeFormatInfo.InvariantInfo) + "\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            dirPath += DateTime.Now.ToString("MM", DateTimeFormatInfo.InvariantInfo) + "\\";
            folder += DateTime.Now.ToString("MM", DateTimeFormatInfo.InvariantInfo) + "\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            dirPath += DateTime.Now.ToString("dd", DateTimeFormatInfo.InvariantInfo) + "\\";
            folder += DateTime.Now.ToString("dd", DateTimeFormatInfo.InvariantInfo) + "\\";
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            return dirPath;
        }
        private static void log(string log_details)
        {
            try
            {

                StreamWriter sw = new StreamWriter(GetUpLoadDirPath() + "Log.log", true);
                sw.WriteLine(log_details);
                sw.Close();
            }
            catch (Exception err)
            {
                //io err
            }
        }
    }
}
